{% extends 'base.html' %}
{% block content %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>NetEase Cloud Music English Song Search</title>
    <style>
        .search-container {
            margin-bottom: 30px;
        }
        .search-box {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
        }
        input[type="text"] {
            flex: 1;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 16px;
        }
        .results {
            margin-top: 20px;
        }
        .song-item {
            border: 1px solid #eee;
            padding: 15px;
            margin-bottom: 10px;
            border-radius: 5px;
            background-color: #fafafa;
        }
        .song-info {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .song-title {
            font-weight: bold;
            font-size: 18px;
            color: #333;
        }
        .song-artist {
            color: #666;
            font-size: 14px;
        }
        .play-btn {
            background-color: #1db954;
            color: white;
            border: none;
            border-radius: 3px;
            padding: 5px 10px;
            cursor: pointer;
        }
        .play-btn:hover {
            background-color: #1ed760;
        }
        .loading {
            text-align: center;
            padding: 20px;
            color: #666;
        }
        .error {
            color: red;
            text-align: center;
            padding: 10px;
        }
        audio {
            width: 100%;
            margin-top: 10px;
        }
        .player-section {
            margin-top: 30px;
            padding: 20px;
            background-color: #f0f0f0;
            border-radius: 5px;
            display: none;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>NetEase Cloud Music English Song Search</h1>
        
        <div class="search-container">
            <div class="search-box">
                <input type="text" id="searchInput" placeholder="Enter English song name to search...">
                <button onclick="searchSongs()">Search</button>
            </div>
        </div>
        
        <div id="results" class="results"></div>
        
        <div id="playerSection" class="player-section">
            <h3>Now Playing</h3>
            <div id="currentSong"></div>
            <audio id="musicPlayer" controls></audio>
        </div>
    </div>

    <script>
        // Function to search for songs by name
        function searchSongs() {
            const songName = document.getElementById('searchInput').value.trim();
            
            if (!songName) {
                alert('Please enter a song name');
                return;
            }
            
            // Show loading indicator
            document.getElementById('results').innerHTML = '<div class="loading">Searching for songs...</div>';
            
            // Call the API to search for songs by name
            fetch(`/music/get_id/${encodeURIComponent(songName)}`)
                .then(response => response.json())
                .then(data => {
                    // The API returns an object with a "songs" property
                    displayResults(data.songs || []);
                })
                .catch(error => {
                    console.error('Error:', error);
                    document.getElementById('results').innerHTML = '<div class="error">Error searching for songs. Please try again.</div>';
                });
        }
        
        // Function to display search results
        function displayResults(songs) {
            const resultsDiv = document.getElementById('results');
            
            if (!songs || songs.length === 0) {
                resultsDiv.innerHTML = '<div class="error">No songs found. Please try a different search term.</div>';
                return;
            }
            
            let html = '<h3>Search Results:</h3>';
            
            // Limit to 20 results to avoid too many API calls
            const limitedSongs = songs.slice(0, 20);
            
            limitedSongs.forEach(song => {
                html += `
                <div class="song-item">
                    <div class="song-info">
                        <div>
                            <div class="song-title">${song.name || 'Unknown Title'}</div>
                            <div class="song-artist">Artist: ${getArtistNames(song.artists) || 'Unknown'}</div>
                            <div class="song-album">Album: ${song.album ? song.album.name : 'Unknown'}</div>
                        </div>
                        <button class="play-btn" onclick="playSong('${song.id}', '${escapeHtml(song.name || 'Unknown Title')}', '${escapeHtml(getArtistNames(song.artists) || 'Unknown')}')">Play</button>
                    </div>
                </div>
                `;
            });
            
            resultsDiv.innerHTML = html;
        }
        
        // Helper function to get artist names
        function getArtistNames(artists) {
            if (!artists) return 'Unknown';
            return artists.map(artist => artist.name).join(', ');
        }
        
        // Helper function to escape HTML to prevent XSS
        function escapeHtml(text) {
            if (!text) return '';
            return text.toString()
                .replace(/&/g, "&amp;")
                .replace(/</g, "&lt;")
                .replace(/>/g, "&gt;")
                .replace(/"/g, "&quot;")
                .replace(/'/g, "&#039;");
        }
        
        // Function to play a song by ID
        async function playSong(songId, songName, artistName) {
            try {
                // Get the song URL by ID
                const response = await fetch(`/music/get_url/${songId}`);
                
                if (response.status === 204) {
                    alert('Could not get song URL. The song might not be available.');
                    return;
                }
                
                const url = await response.text();
                
                if (url && url.trim() !== '') {
                    // Update player with the song
                    document.getElementById('currentSong').innerHTML = `
                        <strong>${songName}</strong> by <em>${artistName}</em>
                    `;
                    
                    document.getElementById('musicPlayer').src = url;
                    document.getElementById('musicPlayer').load();
                    document.getElementById('musicPlayer').play();
                    
                    // Show player section
                    document.getElementById('playerSection').style.display = 'block';
                } else {
                    alert('Could not get song URL. The song might not be available.');
                }
            } catch (error) {
                console.error('Error getting song URL:', error);
                alert('Error getting song URL. Please try again.');
            }
        }
        
        // Allow Enter key to trigger search
        document.getElementById('searchInput').addEventListener('keypress', function(event) {
            if (event.key === 'Enter') {
                searchSongs();
            }
        });
    </script>
</body>
</html>
{% endblock %}